<template>
  <div class="personal-knowledge">
    <!-- 顶部搜索栏 -->
    <div class="top-search-bar">
      <el-input 
        v-model="searchKeyword" 
        placeholder="输入文件名搜索" 
        style="width: 200px"
        clearable
      />
      <el-input 
        v-model="tagKeyword" 
        placeholder="输入模糊搜索" 
        style="width: 200px"
        clearable
      />
      <el-date-picker
        v-model="dateRange"
        type="daterange"
        range-separator="至"
        start-placeholder="开始日期"
        end-placeholder="结束日期"
        style="width: 240px"
      />
       <div class="button-group">
          <el-button type="primary" @click="handleSearch" :icon="Search" class="search-btn">搜索</el-button>
          <el-button @click="handleReset" :icon="Refresh" class="reset-btn">重置</el-button>
        </div>
    </div>

    <!-- 按钮操作栏 -->
    <div class="button-bar">
      <div class="left-buttons">
        <!-- <el-button type="primary" plain @click="handleNewCategory" :icon="FolderAdd">新增分类</el-button> -->
      </div>
      <div class="right-buttons">
        <el-button type="primary" plain @click="handleUpload" :icon="Upload">上传</el-button>
        <el-button plain @click="handleEdit" :icon="Edit" style="color: #a685ff; border-color: #a685ff; background-color: #f3f0ff;" class="edit-button">修改</el-button>
        <el-button type="danger" plain @click="handleDelete" :icon="Delete">删除</el-button>
      </div>
    </div>

    <div class="main-layout">
      <!-- 左侧分类树 -->
      <div class="left-sidebar">
        <el-tree
          :data="treeData"
          :props="treeProps"
          node-key="id"
          :expand-on-click-node="false"
          :highlight-current="true"
          :current-node-key="selectedNodeId"
          @node-click="handleNodeClick"
          class="category-tree"
        >
          <template #default="{ node, data }">
            <div 
              class="tree-node-content"
              @mouseenter="handleNodeHover(data.id, true)"
              @mouseleave="handleNodeHover(data.id, false)"
            >
              <span class="node-text">{{ node.label }}</span>
            <!--   <div class="node-right">
                <div 
                  v-show="hoveredNodeId === data.id" 
                  class="node-actions"
                  @click.stop
                >
                  <el-button
                    size="small"
                    :icon="Plus"
                    circle
                    @click="handleAddSubCategory(data)"
                    style="background: #a685ff; border-color: #a685ff; color: white;"
                  />
                  <el-button 
                    size="small" 
                    type="danger" 
                    :icon="Minus" 
                    circle
                    @click="handleDeleteCategory(data)"
                  />
                </div>
              </div> -->
            </div>
          </template>
        </el-tree>
      </div>

      <!-- 右侧内容区 -->
      <div class="right-content">
        <!-- 文件表格 -->
        <div class="table-container">
          <el-table
            :data="paginatedTableData"
            style="width: 100%"
            height="100%"
            v-loading="loading"
            @selection-change="handleSelectionChange"
          >
          <el-table-column type="selection" width="55" />
          <el-table-column label="缩略图" width="80">
            <template #default="scope">
              <el-image
                :src="scope.row.preview_img"
                style="width: 40px; height: 40px"
                fit="cover"
                :preview-src-list="[scope.row.preview_img]"
              />
            </template>
          </el-table-column>
          <el-table-column prop="file_name" label="文档名称" min-width="180" show-overflow-tooltip />
          <el-table-column prop="file_category_name" label="所属分类" min-width="120" show-overflow-tooltip />
          <el-table-column prop="document_type_name" label="文档类型" min-width="120" show-overflow-tooltip />
          <el-table-column label="标签" min-width="150" show-overflow-tooltip>
            <template #default="scope">
              <div v-if="parseStringifiedArray(scope.row.label).length > 0">
                <div class="tags-container">
                  <el-tag 
                    v-for="(tag, index) in parseStringifiedArray(scope.row.label).slice(0, 3)" 
                    :key="tag" 
                    size="small" 
                    type="primary"
                    effect="light"
                    class="tag-item"
                  >
                    {{ tag }}
                  </el-tag>
                  <el-tag 
                    v-if="parseStringifiedArray(scope.row.label).length > 3" 
                    size="small" 
                    type="info"
                    effect="plain"
                    class="more-tag"
                  >
                    +{{ parseStringifiedArray(scope.row.label).length - 3 }}
                  </el-tag>
                </div>
              </div>
              <span v-else class="no-data"></span>
            </template>
          </el-table-column>
          <el-table-column label="关键词" min-width="150" show-overflow-tooltip>
            <template #default="scope">
              <div v-if="parseStringifiedArray(scope.row.knowledge_keyword).length > 0">
                <div class="keywords-container">
                  <el-tag 
                    v-for="(keyword, index) in parseStringifiedArray(scope.row.knowledge_keyword).slice(0, 3)" 
                    :key="keyword" 
                    size="small" 
                    type="success"
                    effect="light"
                    class="keyword-item"
                  >
                    {{ keyword }}
                  </el-tag>
                  <el-tag 
                    v-if="parseStringifiedArray(scope.row.knowledge_keyword).length > 3" 
                    size="small" 
                    type="info"
                    effect="plain"
                    class="more-keyword"
                  >
                    +{{ parseStringifiedArray(scope.row.knowledge_keyword).length - 3 }}
                  </el-tag>
                </div>
              </div>
              <span v-else class="no-data"></span>
            </template>
          </el-table-column>
          
          <el-table-column prop="uploader" label="上传者" min-width="100" />
          <el-table-column label="创建时间" min-width="160">
            <template #default="scope">
              <span>{{ formatCreateTime(scope.row.create_time) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="100" fixed="right">
            <template #default="scope">
              <el-button 
                size="small"
                @click="handleView(scope.row)" 
                style="background: linear-gradient(90deg, #5b7cff 0%, #a685ff 100%);color:aliceblue"
              >
                详情
              </el-button>
            </template>
          </el-table-column>
          </el-table>
        </div>

        <!-- 分页 - 右下角固定 -->
        <div class="pagination-fixed">
          <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :page-sizes="[10, 20, 50, 100]"
            :total="total || 0"
            layout="total, sizes, prev, pager, next"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            small
            :hide-on-single-page="false"
          />
        </div>
      </div>
    </div>
    <!-- 新增分类对话框 -->
    <NewCategoryDialog
      v-model:visible="newCategoryDialogVisible"
      :form-data="newCategoryForm"
      :category-options="categoryOptions"
      @confirm="handleCreateCategory"
      @cancel="handleCancelCategory"
    />
    <!-- 删除确认对话框 -->
    <DeleteConfirmDialog
      v-model:visible="deleteConfirmVisible"
      :selected-count="selectedRows.length"
      @confirm="handleDeleteConfirm"
      @cancel="handleDeleteCancel"
    />
    <!-- 删除分类确认对话框 -->
    <DeleteCategoryDialog
      v-model:visible="deleteCategoryConfirmVisible"
      :category-name="categoryToDelete?.name"
      @confirm="handleDeleteCategoryConfirm"
      @cancel="handleDeleteCategoryCancel"
    />

    <!-- 文件详情抽屉 -->
    <FileDetailDrawer
      v-model:visible="drawerVisible"
      :file-detail="currentFileDetail"
      v-model:active-drawer-tab="activeDrawerTab"
      :mock-files="mockFiles"
      @download="downloadFile"
      @preview="previewFile"
    />

    <!-- 文件预览弹窗 -->
    <FilePreviewDialog
      v-model:visible="previewDialogVisible"
      :current-preview-file="currentPreviewFile"
      @close="handlePreviewClose"
    />

    <!-- 上传文档抽屉 -->
    <UploadDocumentDrawer
      v-model:visible="uploadDialogVisible"
      :current-step="currentStep"
      :upload-form="uploadForm"
      :flat-categories="flatCategories"
      :tree-categories="treeData"
      :enterprise-categories="enterpriseCategories"
      :suggested-keywords="suggestedKeywords"
      :uploaded-doc-files="uploadedDocFiles"
      :ai-review-results="aiReviewResults"
      :is-edit-mode="isEditMode"
      :editing-doc-id="editingDocId"
      @close="handleUploadDialogClose"
      @update:upload-form="handleUploadFormUpdate"
      @upload-submit="handleUploadSubmit"
      @previous-step="handlePreviousStep"
      @file-upload="handleFileUpload"
      @drop="handleDrop"
      @drag-over="handleDragOver"
      @trigger-upload="triggerUpload"
      @preview-uploaded-file="previewUploadedFile"
      @remove-uploaded-file="removeUploadedFile"
      @show-conflict-detail="showConflictDetail"
      @download-conflict-file="downloadConflictFile"
      @get-file-icon-class="getFileIconClass"
      @get-file-extension="getFileExtension"
      @format-file-size="formatFileSize"
    />


    <!-- 冲突详情弹窗 -->
    <ConflictDetailDialog
      v-model:visible="conflictDetailVisible"
      :current-conflict-file="currentConflictFile"
      @close="handleCloseConflictDetail"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import {
  FolderAdd,
  Delete,
  Upload,
  Edit,
  Search,
  Refresh,
  Plus,
  Minus
} from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import NewCategoryDialog from './components/NewCategoryDialog.vue'
import DeleteConfirmDialog from './components/DeleteConfirmDialog.vue'
import DeleteCategoryDialog from './components/DeleteCategoryDialog.vue'
import FileDetailDrawer from './components/FileDetailDrawer.vue'
import FilePreviewDialog from './components/FilePreviewDialog.vue'
import UploadDocumentDrawer from './components/UploadDocumentDrawer.vue'
import ConflictDetailDialog from './components/ConflictDetailDialog.vue'
import {getOrgKnowledgeCategory, getKnowledgeByList, uploadFile, uploadKnowledge, type KnowledgeListParams, type KnowledgeListItem, type UploadKnowledgeParams} from "@/api/knowledge/api.ts";
import { formatCreateTime } from '@/utils/dateFormat'

const searchKeyword = ref('')
const tagKeyword = ref('')
const dateRange = ref<[Date, Date] | null>(null)
const currentPage = ref(1)
const pageSize = ref(10)
const hoveredNodeId = ref<string | null>(null)
const selectedNodeId = ref<string | null>(null)
const selectedRows = ref<any[]>([])

// 新增分类对话框
const newCategoryDialogVisible = ref(false)
const newCategoryForm = ref({
  name: '',
  parentId: '',
  parentName: ''
})

// 删除确认对话框
const deleteConfirmVisible = ref(false)
const deleteConfirmResolve = ref<((value: boolean) => void) | null>(null)

// 删除分类确认对话框
const deleteCategoryConfirmVisible = ref(false)
const deleteCategoryConfirmResolve = ref<((value: boolean) => void) | null>(null)
const categoryToDelete = ref<any>(null)

// 树组件配置
const treeProps = {
  children: 'children',
  label: 'type_name'
}

// 树结构数据 
const treeData = ref<any[]>([])
getOrgKnowledgeCategory().then((res) => {
  console.log('API response:', res)  
  // 将扁平化数据转换为树形结构
  treeData.value = buildTreeFromFlatData(res || [])
  console.log('Tree data after conversion:', treeData.value)
  // 初始化时获取知识库列表数据
  fetchKnowledgeList()
})

// 将扁平化的分类数据转换为树形结构
const buildTreeFromFlatData = (flatData: any[]) => {
  // 创建ID到节点的映射
  const nodeMap = new Map()
  flatData.forEach(category => {
    nodeMap.set(category.id, {
      ...category,
      children: []
    })
  })
  
  // 构建树形结构
  const tree: any[] = []
  flatData.forEach(category => {
    const node = nodeMap.get(category.id)
    if (category.parent_id === null) {
      // 根节点
      tree.push(node)
    } else {
      // 子节点
      const parent = nodeMap.get(category.parent_id)
      if (parent) {
        parent.children.push(node)
      }
    }
  })
  
  return tree
}

// 获取扁平化的分类选项（用于下拉框）
const getCategoryOptions = (nodes: any[]) => {
  const options: { label: string; value: string }[] = []
  
  const traverse = (nodes: any[], level = 0) => {
    nodes.forEach(node => {
      const prefix = '　'.repeat(level) // 使用全角空格缩进
      options.push({
        label: prefix + node.type_name,
        value: node.id
      })
      if (node.children && node.children.length > 0) {
        traverse(node.children, level + 1)
      }
    })
  }
  
  traverse(nodes)
  return options
}

const categoryOptions = computed(() => getCategoryOptions(treeData.value))

// 获取所有子节点ID的函数
const getAllChildrenIds = (node: any): string[] => {
  const ids: string[] = [node.id]
  if (node.children && node.children.length > 0) {
    node.children.forEach((child: any) => {
      ids.push(...getAllChildrenIds(child))
    })
  }
  return ids
}

// 递归查找节点的函数
const findNodeById = (nodes: any[], targetId: string): any => {
  for (const node of nodes) {
    if (node.id === targetId) {
      return node
    }
    if (node.children && node.children.length > 0) {
      const found = findNodeById(node.children, targetId)
      if (found) return found
    }
  }
  return null
}

// 表格数据
const tableData = ref<KnowledgeListItem[]>([])
const total = ref(0)
const loading = ref(false)

// 获取知识库列表数据
const fetchKnowledgeList = async (params?: Partial<KnowledgeListParams>) => {
  loading.value = true
  try {
    const requestParams: KnowledgeListParams = {
      file_category: params?.file_category || '', // 左侧分类的id
      description: params?.description || '',
      knowledge_type: params?.knowledge_type || '', // 文档类型
      file_name: params?.file_name || '',
      page: currentPage.value,
      page_size: pageSize.value
    }
    console.log(1111111111111111)
    const response = await getKnowledgeByList(requestParams)
    console.log('response', response)
    tableData.value = response?.items || []
    total.value = response.total || 0
  } catch (error) {
    console.error('获取知识库列表失败:', error)
    ElMessage.error('获取知识库列表失败')
  } finally {
    loading.value = false
  }
}

// 分页数据计算属性
const paginatedTableData = computed(() => {
  return tableData.value
})

// 事件处理函数
const handleNodeHover = (nodeId: string, isHover: boolean) => {
  hoveredNodeId.value = isHover ? nodeId : null
}

const handleAddSubCategory = (data: any) => {
  newCategoryForm.value.parentId = data.id
  newCategoryForm.value.parentName = data.name
  newCategoryDialogVisible.value = true
}

const handleDeleteCategory = async (data: any) => {
  categoryToDelete.value = data
  
  try {
    const confirmed = await showDeleteCategoryConfirm()
    if (!confirmed) return

    // 递归删除分类及其子分类
    const deleteNode = (nodes: any[], targetId: string): boolean => {
      for (let i = 0; i < nodes.length; i++) {
        if (nodes[i].id === targetId) {
          nodes.splice(i, 1)
          return true
        }
        if (nodes[i].children && deleteNode(nodes[i].children, targetId)) {
          return true
        }
      }
      return false
    }

    deleteNode(treeData.value, data.id)
    
    // 如果删除的是当前选中的分类，清空选择并重新获取数据
    if (selectedNodeId.value === data.id || selectedNodeId.value?.startsWith(data.id + '-')) {
      selectedNodeId.value = null
      fetchKnowledgeList()
    } else {
      // 重新获取当前分类的数据
      fetchKnowledgeList({
        file_category: selectedNodeId.value || '' // 左侧分类的id
      })
    }

    ElMessage.success(`分类"${data.name}"删除成功`)
  } catch {
    // 用户取消删除
  }
}

const handleSearch = () => {
  console.log('搜索', { searchKeyword: searchKeyword.value, tagKeyword: tagKeyword.value, dateRange: dateRange.value })
  // 重置到第一页
  currentPage.value = 1
  // 调用API获取数据
  fetchKnowledgeList({
    file_name: searchKeyword.value,
    description: tagKeyword.value,
    file_category: selectedNodeId.value || '' // 左侧分类的id
  })
}

const handleReset = () => {
  searchKeyword.value = ''
  tagKeyword.value = ''
  dateRange.value = null
  selectedNodeId.value = null
  // 重置到第一页并重新获取数据
  currentPage.value = 1
  fetchKnowledgeList()
}

const handleNewCategory = () => {
  newCategoryForm.value.parentId = ''
  newCategoryForm.value.parentName = ''
  newCategoryDialogVisible.value = true
}

const handleNodeClick = (data: any) => {
  console.log('选中节点', data)
  selectedNodeId.value = data.id

  // 重置到第一页
  currentPage.value = 1
  // 清空选择
  selectedRows.value = []
  
  // 调用API获取对应分类的数据
  fetchKnowledgeList({
    file_category: data.id // 左侧分类的id
  })
}

const handleUpload = () => {
  console.log('上传')
  uploadDialogVisible.value = true
}

// 触发文件选择
const triggerUpload = () => {
  fileInputRef.value?.click()
}

// 处理文件上传
const handleFileUpload = async (event: Event) => {
  const target = event.target as HTMLInputElement
  const files = target.files

  if (files) {
    for (const file of Array.from(files)) {
      // 验证文件大小 (20MB限制)
      const maxSize = 20 * 1024 * 1024 // 20MB
      if (file.size > maxSize) {
        ElMessage.error(`文件 ${file.name} 大小超过20MB限制，请选择更小的文件`)
        continue
      }

      // 验证文件类型
      const allowedExtensions = ['doc', 'docx', 'pdf']
      const fileExtension = file.name.split('.').pop()?.toLowerCase()
      
      if (!fileExtension || !allowedExtensions.includes(fileExtension)) {
        ElMessage.error(`文件 ${file.name} 类型不支持，仅支持 Word、PDF文件`)
        continue
      }

      try {
        // 调用上传API
        const response = await uploadFile(file)
        console.log('response', response)
          const uploadedFile = {
            id: Date.now().toString() + Math.random().toString(36).substring(2, 11),
            name: file.name,
            size: file.size,
            type: file.type,
            file: file,
            uploadResponse: response // 保存上传响应数据
          }
          uploadedDocFiles.value.push(uploadedFile)
          ElMessage.success(`文件 ${file.name} 上传成功`)
        
      } catch (error) {
        console.error('文件上传失败:', error)
        ElMessage.error(`文件 ${file.name} 上传失败`)
      }
    }
    
    // 自动选中最新上传的文件
    if (uploadedDocFiles.value.length > 0) {
      const latestFile = uploadedDocFiles.value[uploadedDocFiles.value.length - 1]
      // 通过 emit 通知子组件选中该文件
      setTimeout(() => {
        // 这里可以通过一个自定义事件来通知子组件选中文件
        // 暂时使用一个简单的方法：在下一个 tick 后自动选中
      }, 100)
    }
  }

  // 清空文件输入框
  if (target) {
    target.value = ''
  }
}

// 处理拖拽上传
const handleDrop = async (event: DragEvent) => {
  event.preventDefault()
  const files = event.dataTransfer?.files

  if (files) {
    for (const file of Array.from(files)) {
      // 验证文件大小 (20MB限制)
      const maxSize = 20 * 1024 * 1024 // 20MB
      if (file.size > maxSize) {
        ElMessage.error(`文件 ${file.name} 大小超过20MB限制，请选择更小的文件`)
        continue
      }

      // 验证文件类型
      const allowedExtensions = ['doc', 'docx', 'pdf']
      const fileExtension = file.name.split('.').pop()?.toLowerCase()
      
      if (!fileExtension || !allowedExtensions.includes(fileExtension)) {
        ElMessage.error(`文件 ${file.name} 类型不支持，仅支持 Word、PDF文件`)
        continue
      }

      try {
        // 调用上传API
        const response = await uploadFile(file)
        console.log('response', response)
          const uploadedFile = {
            id: Date.now().toString() + Math.random().toString(36).substring(2, 11),
            name: file.name,
            size: file.size,
            type: file.type,
            file: file,
            uploadResponse: response // 保存上传响应数据
          }
          console.log('uploadedFile', uploadedFile)
          uploadedDocFiles.value.push(uploadedFile)
          ElMessage.success(`文件 ${file.name} 上传成功`)
      } catch (error) {
        console.error('文件上传失败:', error)
        ElMessage.error(`文件 ${file.name} 上传失败`)
      }
    }
  }
}

// 处理拖拽悬停
const handleDragOver = (event: DragEvent) => {
  event.preventDefault()
}

// 移除已上传的文件
const removeUploadedFile = (fileId: string) => {
  const index = uploadedDocFiles.value.findIndex(file => file.id === fileId)
  if (index > -1) {
    uploadedDocFiles.value.splice(index, 1)
  }
}

// 预览已上传的文件
const previewUploadedFile = (file: any) => {
  console.log('预览上传的文件:', file)

  // 创建文件URL用于预览
  if (file.file) {
    const fileURL = URL.createObjectURL(file.file)
    const fileExtension = file.name.split('.').pop()?.toLowerCase()

    if (['jpg', 'jpeg', 'png', 'gif', 'bmp'].includes(fileExtension || '')) {
      // 图片预览
      const img = new Image()
      img.src = fileURL
      const newWindow = window.open('', '_blank')
      if (newWindow) {
        newWindow.document.write(`<img src="${fileURL}" style="max-width: 100%; height: auto;">`)
      }
    } else if (fileExtension === 'pdf') {
      // PDF预览
      window.open(fileURL, '_blank')
    } else {
      // 其他文件类型提示下载
      ElMessage.info('该文件类型暂不支持预览，请下载后查看')
      const link = document.createElement('a')
      link.href = fileURL
      link.download = file.name
      link.click()
    }

    // 清理URL对象
    setTimeout(() => URL.revokeObjectURL(fileURL), 1000)
  } else {
    ElMessage.warning('文件数据不完整，无法预览')
  }
}

// 格式化文件大小
const formatFileSize = (bytes: number): string => {
  if (bytes === 0) return '0 B'
  const k = 1024
  const sizes = ['B', 'KB', 'MB', 'GB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return parseFloat((bytes / Math.pow(k, i)).toFixed(1)) + ' ' + sizes[i]
}

// 处理表单更新
const handleUploadFormUpdate = (newForm: any) => {
  console.log('父组件接收到表单更新:', newForm)
  uploadForm.value = { ...newForm } // 使用展开运算符确保数据更新
}

// 关闭上传弹窗
const handleUploadDialogClose = () => {
  uploadDialogVisible.value = false
  currentStep.value = 1 // 重置步骤
  uploadForm.value = {
    categoryId: '',
    documentType: '',
    keywords: [],
    searchScope: [],
    documentOverview: ''
  }
  uploadedDocFiles.value = []

  // 重置编辑模式
  isEditMode.value = false
  editingDocId.value = null
}

// 提交审核（第一步）
const handleUploadSubmit = async () => {
  // 验证表单
  if (!uploadForm.value.categoryId) {
    ElMessage.warning('请选择文档分类')
    return
  }
  if (!uploadForm.value.documentType) {
    ElMessage.warning('请选择文档类型')
    return
  }
  if (uploadedDocFiles.value.length === 0) {
    ElMessage.warning('请上传至少一个文件')
    return
  }

  try {
    // 获取第一个上传的文件（假设只上传一个文件）
    const uploadedFile = uploadedDocFiles.value[0]
    console.log('uploadedFile', uploadedFile)
    console.log('uploadForm.value:', uploadForm.value)
    
    // 构建上传参数
    const uploadParams: UploadKnowledgeParams = {
      document_type: 'c56sa13csa123',
      // uploadForm.value.documentType || '',
      key_word: uploadForm.value.keywords || [],
      scope: '1', // 固定值
      url: uploadedFile.uploadResponse?.file_url || '', // 上传文件的地址
      file_name: uploadedFile.name,
      tos_path: uploadedFile.uploadResponse?.prefix || '', // 文件路径
      label: uploadForm.value.searchScope || [], // 标签
      meta_id: uploadedFile.uploadResponse?.meta?.doc_id || '', // 上传文件接口返回的meta_id
      description: uploadForm.value.documentOverview || '', // 文档概述
      file_category: uploadForm.value.categoryId || '' // 文档分类
    }

    console.log('上传知识库参数:', uploadParams)
    console.log('key_word:', uploadParams.key_word)
    console.log('label:', uploadParams.label)
    
    // 调用上传知识库API
    const response = await uploadKnowledge(uploadParams)
      ElMessage.success('文档上传成功！')
      // 重新获取知识库列表
      fetchKnowledgeList({
        file_name: searchKeyword.value,
        description: tagKeyword.value,
        file_category: selectedNodeId.value || '' // 左侧分类的id
      })
      // 关闭上传弹窗
      handleUploadDialogClose()
  } catch (error) {
    console.error('文档上传失败:', error)
    ElMessage.error('文档上传失败')
  }
}

// 返回上一步
const handlePreviousStep = () => {
  currentStep.value = 1
}

// 最终提交（第二步）
const handleFinalSubmit = async () => {
  if (isEditMode.value) {
    console.log('修改文档:', editingDocId.value, uploadForm.value)
    
    try {
      // 构建更新参数
      const updateParams = {
        id: editingDocId.value,
        document_type: uploadForm.value.documentType || '',
        key_word: uploadForm.value.keywords || [],
        label: uploadForm.value.searchScope || [],
        description: uploadForm.value.documentOverview || '',
        file_category: uploadForm.value.categoryId || ''
      }
      
      // TODO: 调用更新API
      // const response = await updateKnowledge(updateParams)
      
      // 模拟更新成功
      ElMessage.success('文档修改成功！')
      
      // 重新获取知识库列表
      fetchKnowledgeList({
        file_name: searchKeyword.value,
        description: tagKeyword.value,
        file_category: selectedNodeId.value || ''
      })
      
      handleUploadDialogClose()
    } catch (error) {
      console.error('文档修改失败:', error)
      ElMessage.error('文档修改失败')
    }
    return
  }

  // 检查是否有上传的文件
  if (uploadedDocFiles.value.length === 0) {
    ElMessage.warning('请先上传文件')
    return
  }

  try {
    // 获取第一个上传的文件（假设只上传一个文件）
    const uploadedFile = uploadedDocFiles.value[0]
    
    // 构建上传参数
    const uploadParams: UploadKnowledgeParams = {
      document_type: uploadForm.value.documentType || '',
      key_word: uploadForm.value.keywords || [],
      scope: '1', // 固定值
      url: uploadedFile.uploadResponse?.url || '', // 上传文件的地址
      file_name: uploadedFile.name,
      tos_path: uploadedFile.uploadResponse?.tos_path || '', // 文件路径
      label: uploadForm.value.searchScope || [], // 标签
      meta_id: uploadedFile.uploadResponse?.meta?.doc_id || '', // 上传文件接口返回的meta_id
      description: uploadForm.value.documentOverview || '', // 文档概述
      file_category: uploadForm.value.categoryId || '', // 文档分类
      knowledge_type: uploadForm.value.categoryId || '' // 文档类型
    }

    console.log('上传知识库参数:', uploadParams)
    
    // 调用上传知识库API
    const response = await uploadKnowledge(uploadParams)
    
    if (response.success) {
      ElMessage.success('文档上传成功！')
      // 重新获取知识库列表
      fetchKnowledgeList({
        file_name: searchKeyword.value,
        description: tagKeyword.value,
        file_category: selectedNodeId.value || '' // 左侧分类的id
      })
    } else {
      ElMessage.error(`文档上传失败: ${response.message}`)
    }
  } catch (error) {
    console.error('文档上传失败:', error)
    ElMessage.error('文档上传失败')
  }
  
  handleUploadDialogClose()
}

// 显示冲突详情
const showConflictDetail = (file: any) => {
  if (file.status !== 'error') {
    ElMessage.warning('只有冲突文件才能查看详情')
    return
  }

  // 设置冲突详情数据
  currentConflictFile.value = {
    ...file,
    conflictDetails: [
      {
        type: '内容重复',
        description: '与现有文档《企业管理制度汇编》存在80%内容重复',
        existingFile: '企业管理制度汇编.docx',
        similarity: '80%'
      },
      {
        type: '关键词冲突',
        description: '关键词"管理制度"与3个现有文档冲突',
        conflictCount: 3
      }
    ]
  }

  conflictDetailVisible.value = true
  console.log('显示冲突详情:', file)
}

// 下载冲突文件
const downloadConflictFile = (file: any) => {
  if (file.status !== 'error') {
    ElMessage.warning('只有冲突文件才能下载')
    return
  }

  // 模拟下载冲突报告
  const conflictReport = {
    filename: file.filename,
    conflictType: '内容重复冲突',
    conflictDetails: '与现有文档存在重复内容',
    suggestion: '建议修改文档内容或合并相似文档'
  }

  const dataStr = JSON.stringify(conflictReport, null, 2)
  const dataBlob = new Blob([dataStr], { type: 'application/json' })
  const url = URL.createObjectURL(dataBlob)

  const link = document.createElement('a')
  link.href = url
  link.download = `${file.filename}_冲突报告.json`
  link.click()

  URL.revokeObjectURL(url)
  ElMessage.success('冲突报告下载成功')
  console.log('下载冲突文件:', file.filename)
}

// 关闭冲突详情弹窗
const handleCloseConflictDetail = () => {
  conflictDetailVisible.value = false
  currentConflictFile.value = null
}

// 获取文件图标类
const getFileIconClass = (file: any): string => {
  const extension = getFileExtension(file.name).toLowerCase()

  if (extension === 'pdf') {
    return 'file-icon-pdf'
  } else if (['doc', 'docx'].includes(extension)) {
    return 'file-icon-word'
  } else if (['xls', 'xlsx'].includes(extension)) {
    return 'file-icon-excel'
  } else if (['ppt', 'pptx'].includes(extension)) {
    return 'file-icon-ppt'
  } else if (['txt'].includes(extension)) {
    return 'file-icon-txt'
  } else {
    return 'file-icon-default'
  }
}

// 获取文件扩展名
const getFileExtension = (filename: string): string => {
  const parts = filename.split('.')
  return parts.length > 1 ? parts[parts.length - 1].toUpperCase() : 'FILE'
}

const handleEdit = () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请先选择要修改的文档')
    return
  }

  if (selectedRows.value.length > 1) {
    ElMessage.warning('一次只能修改一个文档')
    return
  }

  const selectedDoc = selectedRows.value[0]
  console.log('编辑文档:', selectedDoc)

  // 解析字符串化数组的辅助函数
  const parseStringifiedArray = (value: string[] | string | undefined): string[] => {
    if (!value) return []
    if (Array.isArray(value)) return value
    if (typeof value === 'string') {
      try {
        const trimmed = value.trim()
        if (trimmed.startsWith('[') && trimmed.endsWith(']')) {
          const content = trimmed.slice(1, -1)
          if (content) {
            return content.split(',').map(item =>
              item.trim().replace(/^['"]|['"]$/g, '')
            ).filter(item => item.length > 0)
          }
        }
        return [value]
      } catch (error) {
        console.error('解析字符串化数组失败:', error)
        return [value]
      }
    }
    return []
  }

  // 回显数据到表单
  uploadForm.value = {
    categoryId: selectedDoc.categoryId || '',
    documentType: selectedDoc.documentType || selectedDoc.document_type || '',
    keywords: parseStringifiedArray(selectedDoc.keywords || selectedDoc.knowledge_keyword),
    searchScope: parseStringifiedArray(selectedDoc.searchScope || selectedDoc.label),
    documentOverview: selectedDoc.documentOverview || selectedDoc.description || ''
  }

  // 设置编辑模式
  isEditMode.value = true
  editingDocId.value = selectedDoc.id

  // 在编辑模式下，创建文件信息用于显示
  uploadedDocFiles.value = [{
    id: selectedDoc.id,
    name: selectedDoc.filename || selectedDoc.file_name,
    size: selectedDoc.size || '未知',
    type: selectedDoc.fileType || selectedDoc.document_type,
    url: selectedDoc.url || '',
    uploadResponse: {
      url: selectedDoc.url || '',
      tos_path: selectedDoc.tos_path || '',
      meta: {
        doc_id: selectedDoc.id
      }
    }
  }]

  // 打开上传抽屉
  uploadDialogVisible.value = true
  currentStep.value = 1
}

const handleDelete = async () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请先选择要删除的文件')
    return
  }

  try {
    const confirmed = await showDeleteConfirm()
    if (!confirmed) return

    // 删除选中的文件后重新获取数据
    // 注意：这里应该调用删除API，然后重新获取数据
    // 暂时只是重新获取当前数据
    fetchKnowledgeList({
      file_name: searchKeyword.value,
      description: tagKeyword.value,
      file_category: selectedNodeId.value || '' // 左侧分类的id
    })

    // 清空选择
    selectedRows.value = []

    ElMessage.success(`成功删除 ${selectedRows.value.length} 个文件`)
  } catch {
    // 用户取消删除
  }
}

// 抽屉相关状态
const drawerVisible = ref(false)
const currentFileDetail = ref<any>(null)
const activeDrawerTab = ref('basic')

// 预览弹窗状态
const previewDialogVisible = ref(false)
const currentPreviewFile = ref<any>(null)

// 上传弹窗状态
const uploadDialogVisible = ref(false)
const uploadForm = ref<{
  categoryId: string
  documentType: string
  keywords: string[]
  searchScope: string[]
  documentOverview: string
}>({
  categoryId: '',
  documentType: '',
  keywords: [],
  searchScope: [],
  documentOverview: ''
})
const uploadedDocFiles = ref<any[]>([])

// 编辑模式状态
const isEditMode = ref(false)
const editingDocId = ref<string | null>(null)
const fileInputRef = ref<HTMLInputElement>()

// 步骤状态管理
const currentStep = ref(1) // 1: 文件上传, 2: AI审核

// 冲突详情弹窗相关
const conflictDetailVisible = ref(false)
const currentConflictFile = ref<any>(null)

// AI审核结果数据
const aiReviewResults = ref([
  {
    id: 1,
    filename: '6 公文管理标准化手册.docx',
    status: 'success',
    statusText: 'AI说明：审核通过',
    category: '分类：政策文件',
    keywords: '关键词：公文管理',
    checkScope: '检索范围：政策文件分类'
  },
  {
    id: 2,
    filename: '5 督查管理.docx',
    status: 'error',
    statusText: 'AI说明：发现内容冲突',
    category: '分类：管理制度',
    keywords: '关键词：督查管理',
    checkScope: '检索范围：管理制度分类'
  },
])

// 建议的关键词
const suggestedKeywords = ref([
  '安全管理', '制度规范', '操作流程', '技术标准', '培训资料',
  '质量控制', '项目管理', '人力资源', '财务管理', '合同管理'
])

// 扁平化的分类选项
const flatCategories = computed(() => {
  const flatten = (categories: any[], result: any[] = []) => {
    categories.forEach(category => {
      result.push({
        id: category.id,
        name: category.name
      })
      if (category.children && category.children.length > 0) {
        flatten(category.children, result)
      }
    })
    return result
  }
  return flatten(treeData.value)
})

// 企业知识库分类数据（用于检索范围选择）
const enterpriseCategories = ref([
  {
    id: 'shiyi-library',
    name: '十一智库-资料',
    icon: '📚',
    children: [
      {
        id: 'external',
        name: '外部',
        children: [
          {
            id: 'regulations',
            name: '规范、图集',
            children: [
              {
                id: 'construction-standards',
                name: '施工规范、图集',
                children: [
                  {
                    id: 'construction-regulations',
                    name: '施工规范',
                    children: [
                      { id: 'national-construction', name: '国家规范' },
                      { id: 'industry-construction', name: '行业规范' },
                      { id: 'local-construction', name: '地方规范' }
                    ]
                  },
                  {
                    id: 'construction-atlas',
                    name: '施工图集',
                    children: [
                      { id: 'national-atlas', name: '国家规范' },
                      { id: 'industry-atlas', name: '行业规范' },
                      { id: 'local-atlas', name: '地方规范' }
                    ]
                  }
                ]
              },
              {
                id: 'design-standards',
                name: '设计规范、图集',
                children: [
                  { id: 'electrical', name: '电' },
                  { id: 'building', name: '建筑' },
                  { id: 'structure', name: '结构' },
                  { id: 'heating', name: '暖' },
                  { id: 'water', name: '水' }
                ]
              }
            ]
          }
        ]
      },
      {
        id: 'internal',
        name: '内部',
        children: [
          {
            id: 'shaanxi-construction-holding',
            name: '陕西建工控股集团有限公司',
            children: [
              { id: 'holding-regulations', name: '制度' },
              { id: 'holding-standards', name: '标准' },
              { id: 'holding-policies', name: '相关办法及通知' }
            ]
          },
          {
            id: 'shaanxi-construction-group',
            name: '陕西建工集团股份有限公司',
            children: [
              { id: 'group-regulations', name: '制度' },
              { id: 'group-standards', name: '标准' },
              { id: 'group-policies', name: '相关办法及通知' }
            ]
          },
          {
            id: 'shaanxi-11th-construction',
            name: '陕西建工第十一建设集团有限公司',
            children: [
              {
                id: 'enterprise-system-compilation',
                name: '企业制度汇编',
                children: [
                  { id: 'business-category', name: '经营类' },
                  { id: 'production-category', name: '生产类' },
                  { id: 'safety-category', name: '安全类' },
                  { id: 'technology-achievement', name: '科技成果类' },
                  { id: 'technical-quality', name: '技术质量类' },
                  { id: 'business-affairs', name: '商务类' },
                  { id: 'finance-category', name: '财务类' },
                  { id: 'hr-management', name: '人力资源与干部管理类' },
                  { id: 'administrative', name: '行政类' },
                  { id: 'party-discipline', name: '党风廉政建设与纪检监察类' },
                  { id: 'audit-category', name: '审计类' },
                  { id: 'worker-rights', name: '职工权益保障类' },
                  { id: 'design-category', name: '设计类' },
                  { id: 'comprehensive-management', name: '综合管理类' }
                ]
              },
              {
                id: 'enterprise-internal-control',
                name: '企业内部控制'
              },
              {
                id: 'standardization-manual',
                name: '标准化手册'
              },
              {
                id: 'process-standards-guide',
                name: '工艺标准指南'
              },
              {
                id: 'professional-knowledge',
                name: '专业知识',
                children: [
                  {
                    id: 'tech-achievements',
                    name: '科技成果',
                    children: [
                      { id: 'papers', name: '论文' },
                      { id: 'patents', name: '专利' },
                      { id: 'construction-methods', name: '工法' }
                    ]
                  },
                  {
                    id: 'excellent-cases',
                    name: '优秀案例',
                    children: [
                      { id: 'enterprise-culture-type', name: '企业文化类' },
                      { id: 'party-innovation-type', name: '党建创新类' }
                    ]
                  },
                  { id: 'case-review-results', name: '案例复盘成果' },
                  { id: 'international-building-standards', name: '国际建筑说明通用规范' }
                ]
              }
            ]
          }
        ]
      }
    ]
  }
])

// 模拟文件数据
const mockFiles = ref([
  { name: '6 公文管理标准化手册.docx', category: 'AI说明：上传成功', status: 'success' },
  { name: '5 督查管理.docx', category: 'AI说明：上传成功', status: 'success' },
  { name: '4 档案管理.docx', category: 'AI说明：上传失败', status: 'error' },
  { name: '3 会议管理标准手册.docx', category: 'AI说明：上传成功', status: 'success' },
  { name: '2 印章标准化手册.docx', category: 'AI说明：上传成功', status: 'success' },
  { name: '1 信访标准化手册.docx', category: 'AI说明：上传失败', status: 'error' }
])

const handleView = (row: any) => {
  console.log('查看', row)
  currentFileDetail.value = row
  activeDrawerTab.value = 'basic' // 默认显示基本信息
  drawerVisible.value = true
}

// 预览文件
const previewFile = (file: any) => {
  console.log('预览文件:', file)
  currentPreviewFile.value = file
  previewDialogVisible.value = true
}

// 关闭预览弹窗
const handlePreviewClose = () => {
  previewDialogVisible.value = false
  currentPreviewFile.value = null
}

// 下载文件
const downloadFile = (file: any) => {
  console.log('下载文件:', file)

  // 创建一个模拟的下载链接
  const link = document.createElement('a')
  link.href = '#' // 这里应该是实际的文件下载URL
  link.download = file.name

  // 模拟下载过程
  ElMessage.success(`正在下载文件: ${file.name}`)

  // 实际项目中应该是这样：
  // link.href = `/api/files/download/${file.id}`
  // document.body.appendChild(link)
  // link.click()
  // document.body.removeChild(link)
}

const handleSelectionChange = (selection: any[]) => {
  selectedRows.value = selection
}

const handleSizeChange = (size: number) => {
  pageSize.value = size
  // 重置到第一页，避免超出范围
  currentPage.value = 1
  console.log('页面大小变化', size)
  // 重新获取数据
  fetchKnowledgeList({
    file_name: searchKeyword.value,
    description: tagKeyword.value,
    file_category: selectedNodeId.value || '' // 左侧分类的id
  })
}

const handleCurrentChange = (page: number) => {
  currentPage.value = page
  console.log('当前页变化', page)
  // 重新获取数据
  fetchKnowledgeList({
    file_name: searchKeyword.value,
    description: tagKeyword.value,
    file_category: selectedNodeId.value || '' // 左侧分类的id
  })
}



// 新增分类相关方法
const handleCreateCategory = () => {
  if (!newCategoryForm.value.name.trim()) {
    ElMessage.warning('请输入分类名称')
    return
  }

  const newCategory = {
    id: `category-${Date.now()}`,
    name: newCategoryForm.value.name,
    icon: '📁',
    children: []
  }

  if (newCategoryForm.value.parentId) {
    // 添加为子分类
    const findAndAddChild = (nodes: any[]) => {
      for (const node of nodes) {
        if (node.id === newCategoryForm.value.parentId) {
          if (!node.children) {
            node.children = []
          }
          node.children.push(newCategory)
          return true
        }
        if (node.children && findAndAddChild(node.children)) {
          return true
        }
      }
      return false
    }
    findAndAddChild(treeData.value)
  } else {
    // 添加为根分类
    treeData.value.push(newCategory)
  }

  ElMessage.success('分类创建成功')
  newCategoryDialogVisible.value = false
  newCategoryForm.value.name = ''
  newCategoryForm.value.parentId = ''
}

const handleCancelCategory = () => {
  newCategoryDialogVisible.value = false
  newCategoryForm.value.name = ''
  newCategoryForm.value.parentId = ''
  newCategoryForm.value.parentName = ''
}

// 删除确认对话框相关方法
function showDeleteConfirm(): Promise<boolean> {
  return new Promise((resolve) => {
    deleteConfirmResolve.value = resolve
    deleteConfirmVisible.value = true
  })
}

function handleDeleteConfirm() {
  deleteConfirmVisible.value = false
  if (deleteConfirmResolve.value) {
    deleteConfirmResolve.value(true)
    deleteConfirmResolve.value = null
  }
}

function handleDeleteCancel() {
  deleteConfirmVisible.value = false
  if (deleteConfirmResolve.value) {
    deleteConfirmResolve.value(false)
    deleteConfirmResolve.value = null
  }
}

// 删除分类确认对话框相关方法
function showDeleteCategoryConfirm(): Promise<boolean> {
  return new Promise((resolve) => {
    deleteCategoryConfirmResolve.value = resolve
    deleteCategoryConfirmVisible.value = true
  })
}

function handleDeleteCategoryConfirm() {
  deleteCategoryConfirmVisible.value = false
  if (deleteCategoryConfirmResolve.value) {
    deleteCategoryConfirmResolve.value(true)
    deleteCategoryConfirmResolve.value = null
  }
}

function handleDeleteCategoryCancel() {
  deleteCategoryConfirmVisible.value = false
  if (deleteCategoryConfirmResolve.value) {
    deleteCategoryConfirmResolve.value(false)
    deleteCategoryConfirmResolve.value = null
  }
}

// 添加解析字符串化数组的工具函数
const parseStringifiedArray = (value: string[] | string | undefined): string[] => {
  if (!value) return []
  if (Array.isArray(value)) return value
  if (typeof value === 'string') {
    try {
      // 尝试解析字符串化的数组，如 "['11']" 或 "['item1', 'item2']"
      const trimmed = value.trim()
      
      // 处理双重字符串化的情况，如 "[\"[]\"]" 或 "['[]']"
      if (trimmed === '["[]"]' || trimmed === "['[]']") {
        return []
      }
      
      if (trimmed.startsWith('[') && trimmed.endsWith(']')) {
        // 移除方括号，按逗号分割，去除引号和空格
        const content = trimmed.slice(1, -1)
        if (content) {
          return content.split(',').map(item => 
            item.trim().replace(/^['"]|['"]$/g, '')
          ).filter(item => item.length > 0)
        } else {
          // 处理空数组的情况，如 "[]"
          return []
        }
      }
      // 如果不是数组格式，作为单个字符串处理
      return [value]
    } catch (error) {
      console.error('解析字符串化数组失败:', error)
      return [value]
    }
  }
  return []
}
</script>

<style scoped>
.personal-knowledge {
  /* height: 100vh; */
  background: #f5f7fa;
  display: flex;
  flex-direction: column;
}

/* 顶部搜索栏 */
.top-search-bar {
  padding: 15px 0 0 0;
  display: flex;
  gap: 15px;
  align-items: center;
  flex-shrink: 0;
}

/* 按钮操作栏 */
.button-bar {
  padding: 15px 0px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-shrink: 0;
}

.left-buttons {
  width: 280px;
  display: flex;
  justify-content: flex-start;
}

.right-buttons {
  flex: 1;
  display: flex;
  gap: 10px;
  justify-content: flex-start;
  margin-left: 10px;
}

/* 主布局 */
.main-layout {
  flex: 1;
  display: flex;
  overflow: hidden;
  min-height: 0;
}

/* 左侧边栏 */
.left-sidebar {
  width: 280px;
  max-height: 700px;
  background: white;
  border-right: 1px solid #e4e7ed;
  display: flex;
  flex-direction: column;
  flex-shrink: 0;
}

.category-tree {
  flex: 1;
  padding: 10px;
  overflow-y: auto;
  min-height: 0;
}

/* 树节点选中状态样式 */
:deep(.el-tree-node.is-current > .el-tree-node__content) {
  background-color: rgba(166, 133, 255, 0.1) !important;
  color: #a685ff !important;
  font-weight: 500;
}

:deep(.el-tree-node__content:hover) {
  background-color: rgba(166, 133, 255, 0.05) !important;
}

:deep(.el-tree-node.is-current > .el-tree-node__content:hover) {
  background-color: rgba(166, 133, 255, 0.15) !important;
}

.tree-node-content {
  display: flex;
  align-items: center;
  width: 100%;
  padding: 2px 0;
}

.node-text {
  flex: 1;
}

.node-right {
  display: flex;
  align-items: center;
  gap: 5px;
}

.node-count {
  background: #f56c6c;
  color: white;
  padding: 2px 6px;
  border-radius: 10px;
  font-size: 12px;
}

.node-count.blue {
  background: #409eff;
}

.node-actions {
  display: flex;
  gap: 4px;
  margin-left: 8px;
}

.node-actions .el-button {
  width: 20px;
  height: 20px;
  padding: 0;
  font-size: 12px;
}

/* 右侧内容区 */
.right-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  margin: 0 10px;
  border-radius: 4px;
  min-height: 0;
  overflow: hidden;
}

/* 表格容器样式 */
.table-container {
  background: white;
  border-radius: 12px;
  margin-bottom: 24px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
  border: 1px solid #e5e7eb;
  overflow: hidden;
  height: 600px;
}

:deep(.table-container .el-table) {
  background-color: #ffffff !important;
  position: relative;
}

:deep(.table-container .el-table__body-wrapper) {
  overflow-x: auto;
  overflow-y: auto;
}

/* 自定义滚动条样式 */
:deep(.table-container .el-table__body-wrapper::-webkit-scrollbar) {
  width: 8px;
  height: 8px;
}

:deep(.table-container .el-table__body-wrapper::-webkit-scrollbar-track) {
  background: #f1f1f1;
  border-radius: 4px;
}

:deep(.table-container .el-table__body-wrapper::-webkit-scrollbar-thumb) {
  background: #c1c1c1;
  border-radius: 4px;
}

:deep(.table-container .el-table__body-wrapper::-webkit-scrollbar-thumb:hover) {
  background: #a8a8a8;
}

/* 表格头部样式 - 与企业库分类保持一致 */
:deep(.table-container .el-table) {
  --el-table-header-bg-color: transparent;
}

:deep(.table-container .el-table__header) {
  background: linear-gradient(135deg, #e0e7ff 0%, #f3e8ff 100%) !important;
}

:deep(.table-container .el-table__header-wrapper) {
  background: linear-gradient(135deg, #e0e7ff 0%, #f3e8ff 100%) !important;
}

:deep(.table-container .el-table__header thead) {
  background: linear-gradient(135deg, #e0e7ff 0%, #f3e8ff 100%) !important;
}

:deep(.table-container .el-table__header thead tr) {
  background: linear-gradient(135deg, #e0e7ff 0%, #f3e8ff 100%) !important;
}

:deep(.table-container .el-table th.el-table__cell) {
  color: #4338ca !important;
  font-weight: 600 !important;
  font-size: 14px !important;
  border-bottom: 1px solid #c7d2fe !important;
  height: 48px !important;
}

:deep(.table-container .el-table tr) {
  background-color: #ffffff !important;
}

:deep(.table-container .el-table--enable-row-hover .el-table__body tr:hover > td) {
  background: #f8fafc !important;
}

:deep(.table-container .el-table__body td) {
  border-bottom: 1px solid #f1f5f9 !important;
}

/* 完全重写固定列样式 */
:deep(.table-container .el-table__fixed-right) {
  right: 0 !important;
  z-index: 999 !important;
  background: #ffffff !important;
  box-shadow: -4px 0 12px rgba(0, 0, 0, 0.15) !important;
  position: absolute !important;
  top: 0 !important;
  bottom: 0 !important;
}

:deep(.table-container .el-table__fixed-right-patch) {
  right: 0 !important;
  background: #ffffff !important;
  z-index: 1000 !important;
}

:deep(.table-container .el-table__fixed-right .el-table__cell) {
  background: #ffffff !important;
  border-left: 2px solid #e4e7ed !important;
}

:deep(.table-container .el-table__fixed-right .el-table__body-wrapper) {
  background: #ffffff !important;
}

:deep(.table-container .el-table__fixed-right .el-table__header-wrapper) {
  background: #ffffff !important;
}

:deep(.table-container .el-table__fixed-right .el-table__header) {
  background: linear-gradient(135deg, #e0e7ff 0%, #f3e8ff 100%) !important;
}

:deep(.table-container .el-table__fixed-right .el-table__header-wrapper) {
  background: linear-gradient(135deg, #e0e7ff 0%, #f3e8ff 100%) !important;
}

:deep(.table-container .el-table__fixed-right .el-table__header thead) {
  background: linear-gradient(135deg, #e0e7ff 0%, #f3e8ff 100%) !important;
}

:deep(.table-container .el-table__fixed-right .el-table__header thead tr) {
  background: linear-gradient(135deg, #e0e7ff 0%, #f3e8ff 100%) !important;
}

:deep(.table-container .el-table__fixed-right .el-table__header-wrapper .el-table__cell) {
  background: linear-gradient(135deg, #e0e7ff 0%, #f3e8ff 100%) !important;
  border-left: 2px solid #e4e7ed !important;
  color: #4338ca !important;
  font-weight: 600 !important;
  padding: 12px 16px !important;
  height: 48px !important;
}

:deep(.table-container .el-table__fixed-right .el-table__row:hover .el-table__cell) {
  background: #f8fafc !important;
}

/* 固定分页 - 右下角 */
.pagination-fixed {
  position: fixed;
  bottom: 24px;
  right: 24px;
  z-index: 100;
  background: white;
  padding: 12px 16px;
  border-radius: 12px;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.15);
  border: 1px solid #e5e7eb;
  display: block !important; /* 强制显示分页组件 */
}

.pagination-fixed :deep(.el-pagination) {
  margin: 0;
  display: flex !important; /* 强制显示分页组件 */
}

.pagination-fixed :deep(.el-pagination .el-pager li) {
  background: transparent;
  border-radius: 6px;
  margin: 0 2px;
  transition: all 0.2s;
}

.pagination-fixed :deep(.el-pagination .el-pager li:hover) {
  background: #f3f4f6;
}

.pagination-fixed :deep(.el-pagination .el-pager li.is-active) {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
}

.pagination-fixed :deep(.el-pagination .btn-prev),
.pagination-fixed :deep(.el-pagination .btn-next) {
  border-radius: 6px;
  transition: all 0.2s;
}

.pagination-fixed :deep(.el-pagination .btn-prev:hover),
.pagination-fixed :deep(.el-pagination .btn-next:hover) {
  background: #f3f4f6;
}

/* 极简对话框样式 */
:deep(.minimal-dialog .el-dialog) {
  background: var(--minimal-glass-bg);
  border-radius: var(--minimal-radius);
  box-shadow: 0 12px 48px 0 rgba(91, 124, 255, 0.15);
  backdrop-filter: blur(var(--minimal-glass-blur));
  border: 1px solid rgba(255, 255, 255, 0.3);
  overflow: hidden;
}

:deep(.minimal-dialog .el-dialog__header) {
  padding: 0;
  margin: 0;
}

:deep(.minimal-dialog .el-dialog__body) {
  padding: 0;
}

:deep(.minimal-dialog .el-dialog__footer) {
  padding: 0;
}

.dialog-header {
  display: flex;
  align-items: center;
  padding: 2em 2.5em 1em 2.5em;
  gap: 1em;
}

.dialog-icon {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  background: var(--minimal-primary-gradient);
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 4px 12px 0 rgba(91, 124, 255, 0.3);
}

.dialog-header h3 {
  font-size: 1.25em;
  font-weight: 600;
  color: var(--minimal-text);
  margin: 0;
  letter-spacing: 0.01em;
}

.dialog-content {
  padding: 0 2.5em 1.5em 2.5em;
}

.dialog-actions {
  display: flex;
  gap: 1em;
  padding: 1.5em 2.5em 2em 2.5em;
  justify-content: flex-end;
}

.minimal-btn {
  padding: 0.7em 2em;
  border: none;
  border-radius: 12px;
  font-size: 0.95em;
  font-family: inherit;
  cursor: pointer;
  transition: all 0.2s ease;
  outline: none;
  font-weight: 500;
  letter-spacing: 0.01em;
  min-width: 80px;
}

.minimal-btn--secondary {
  background: var(--minimal-glass-bg);
  color: var(--minimal-text);
  border: 1px solid var(--minimal-border);
  backdrop-filter: blur(8px);
}

.minimal-btn--secondary:hover {
  background: rgba(0, 0, 0, 0.05);
  border-color: var(--minimal-primary-gradient);
}

.minimal-btn--primary {
  background: var(--minimal-primary-gradient);
  color: white;
  box-shadow: 0 4px 12px 0 rgba(91, 124, 255, 0.25);
}

.minimal-btn--primary:hover {
  box-shadow: 0 6px 16px 0 rgba(91, 124, 255, 0.35);
  transform: translateY(-1px);
}

.minimal-btn--primary:active {
  transform: translateY(0);
}

.minimal-btn--danger {
  background: linear-gradient(135deg, #ff6b6b 0%, #ee5a52 100%);
  color: white;
  box-shadow: 0 4px 12px 0 rgba(255, 107, 107, 0.25);
}

.minimal-btn--danger:hover {
  box-shadow: 0 6px 16px 0 rgba(255, 107, 107, 0.35);
  transform: translateY(-1px);
}

.minimal-btn--danger:active {
  transform: translateY(0);
}

.delete-icon {
  background: linear-gradient(135deg, #ff6b6b 0%, #ee5a52 100%);
}

.confirm-message {
  font-size: 1.1em;
  color: var(--minimal-text);
  margin: 0 0 0.5em 0;
  line-height: 1.5;
}

.confirm-warning {
  font-size: 0.9em;
  color: #999;
  margin: 0;
  line-height: 1.4;
}

/* 表单样式 */
:deep(.minimal-form .el-form-item__label) {
  color: var(--minimal-text);
  font-weight: 500;
}

:deep(.minimal-input .el-input__wrapper) {
  background: var(--minimal-glass-bg);
  border: 1px solid var(--minimal-border);
  border-radius: 12px;
  backdrop-filter: blur(8px);
  transition: all 0.2s ease;
}

:deep(.minimal-input .el-input__wrapper:hover) {
  border-color: var(--minimal-primary-gradient);
}

:deep(.minimal-input .el-input__wrapper.is-focus) {
  border-color: var(--minimal-primary-gradient);
  box-shadow: 0 0 0 2px rgba(91, 124, 255, 0.1);
}

/* 下拉框样式 */
:deep(.minimal-select .el-select__wrapper) {
  background: var(--minimal-glass-bg);
  border: 1px solid var(--minimal-border);
  border-radius: 12px;
  backdrop-filter: blur(8px);
  transition: all 0.2s ease;
}

:deep(.minimal-select .el-select__wrapper:hover) {
  border-color: var(--minimal-primary-gradient);
}

:deep(.minimal-select .el-select__wrapper.is-focused) {
  border-color: var(--minimal-primary-gradient);
  box-shadow: 0 0 0 2px rgba(91, 124, 255, 0.1);
}

:deep(.minimal-select .el-select__placeholder) {
  color: #999;
}

:deep(.el-select-dropdown) {
  background: var(--minimal-glass-bg);
  border: 1px solid var(--minimal-border);
  border-radius: 12px;
  backdrop-filter: blur(12px);
  box-shadow: 0 8px 32px 0 rgba(91, 124, 255, 0.15);
}

:deep(.el-select-dropdown .el-select-dropdown__item) {
  color: var(--minimal-text);
  transition: all 0.2s ease;
}

:deep(.el-select-dropdown .el-select-dropdown__item:hover) {
  background: rgba(91, 124, 255, 0.1);
}

:deep(.el-select-dropdown .el-select-dropdown__item.is-selected) {
  background: var(--minimal-primary-gradient);
  color: white;
}

/* 修改按钮样式 */
:deep(.el-button.is-plain) {
  transition: all 0.3s ease;
}

/* :deep(.el-button.is-plain:hover) {
  background-color: #a685ff !important;
  color: white !important;
  border-color: #a685ff !important;
} */
/* 修改按钮样式 */
:deep(.edit-button.el-button.is-plain:hover) {
  background-color: #a685ff !important;
  color: white !important;
  border-color: #a685ff !important;
}

/* 表格勾选框颜色修改为紫色 */
:deep(.el-checkbox__input.is-checked .el-checkbox__inner) {
  background-color: #a685ff !important;
  border-color: #a685ff !important;
}

:deep(.el-checkbox__input.is-indeterminate .el-checkbox__inner) {
  background-color: #a685ff !important;
  border-color: #a685ff !important;
}

:deep(.el-checkbox__input.is-checked + .el-checkbox__label) {
  color: #a685ff !important;
}

:deep(.el-checkbox__input.is-focus .el-checkbox__inner) {
  border-color: #a685ff !important;
}

:deep(.el-checkbox__inner:hover) {
  border-color: #a685ff !important;
}

/* 表格行选中状态 */
:deep(.table-container .el-table__row.current-row) {
  background-color: rgba(166, 133, 255, 0.1) !important;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .pagination-fixed {
    position: static;
    margin-top: 16px;
    border-radius: 8px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  }

  .table-container {
    border-radius: 12px;
  }

  .table-container :deep(.el-table__header th),
  .table-container :deep(.el-table__body td) {
    padding: 8px 12px !important;
  }
}

@media (max-width: 480px) {
  :deep(.minimal-dialog .el-dialog) {
    width: 90% !important;
    margin: 1rem;
  }

  .dialog-header,
  .dialog-content,
  .dialog-actions {
    padding-left: 1.5em;
    padding-right: 1.5em;
  }

  .dialog-actions {
    flex-direction: column;
  }

  .minimal-btn {
    width: 100%;
  }
}

/* 文件详情抽屉样式 */
:deep(.file-detail-drawer .el-drawer) {
  background: #ffffff;
}

:deep(.file-detail-drawer .el-drawer__header) {
  padding: 0;
  margin-bottom: 0;
  border-bottom: 1px solid #f0f0f0;
}

.drawer-header {
  padding: 20px 24px;
  background: #ffffff;
}

.drawer-title {
  display: flex;
  align-items: center;
  gap: 12px;
  font-size: 18px;
  font-weight: 600;
  color: #333;
}

.title-bar {
  width: 4px;
  height: 20px;
  background: linear-gradient(135deg, #5b7cff 0%, #a685ff 100%);
  border-radius: 2px;
}

.drawer-content {
  padding: 0 24px 24px;
}

.drawer-tabs {
  display: flex;
  border-bottom: 1px solid #f0f0f0;
  margin-bottom: 24px;
}

.tab-item {
  padding: 12px 0;
  margin-right: 32px;
  font-size: 14px;
  color: #666;
  cursor: pointer;
  position: relative;
  transition: color 0.3s ease;
}

.tab-item.active {
  color: #5b7cff;
  font-weight: 500;
}

.tab-item.active::after {
  content: '';
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  height: 2px;
  background: linear-gradient(135deg, #5b7cff 0%, #a685ff 100%);
  border-radius: 1px;
}

.file-list {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.file-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 0;
  border-bottom: 1px solid #f5f5f5;
}

.file-item:last-child {
  border-bottom: none;
}

.file-info {
  flex: 1;
}

.file-name {
  font-size: 14px;
  color: #333;
  margin-bottom: 8px;
  font-weight: 500;
}

.file-tag {
  display: inline-block;
  padding: 4px 12px;
  font-size: 12px;
  border-radius: 12px;
  border: 1px solid;
}

.file-tag.success {
  background: #e8f5e8;
  color: #52c41a;
  border-color: #b7eb8f;
}

.file-tag.error {
  background: #fff2f0;
  color: #ff4d4f;
  border-color: #ffccc7;
}

.file-actions {
  display: flex;
  gap: 8px;
}

.file-actions .el-button {
  font-size: 12px;
  padding: 6px 12px;
}

/* 基本信息样式 */
.basic-info {
  padding: 16px 0;
}

.info-section {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.info-row {
  display: flex;
  align-items: flex-start;
  gap: 12px;
}

.info-label {
  min-width: 80px;
  font-size: 14px;
  color: #666;
  font-weight: 500;
  flex-shrink: 0;
}

.info-value {
  flex: 1;
  font-size: 14px;
  color: #333;
  line-height: 1.5;
}

.info-value .el-tag {
  margin-right: 8px;
  margin-bottom: 4px;
}

/* 预览弹窗样式 */
:deep(.preview-dialog .el-dialog) {
  border-radius: 8px;
  overflow: hidden;
  max-height: 90vh;
}

:deep(.preview-dialog .el-dialog__header) {
  padding: 0;
  margin-bottom: 0;
  border-bottom: 1px solid #f0f0f0;
  background: #ffffff;
}

.preview-dialog-header {
  padding: 20px 24px;
  background: #ffffff;
}

.preview-title {
  display: flex;
  align-items: center;
  gap: 12px;
  font-size: 18px;
  font-weight: 600;
  color: #333;
}

.preview-title .title-bar {
  width: 4px;
  height: 20px;
  background: linear-gradient(135deg, #5b7cff 0%, #a685ff 100%);
  border-radius: 2px;
}

/* 上传抽屉样式 */
:deep(.create-doc-drawer .el-drawer) {
  border-radius: 12px 0 0 12px;
  overflow: hidden;
}

:deep(.create-doc-drawer .el-drawer__header) {
  padding: 0;
  margin-bottom: 0;
  border-bottom: 1px solid #f0f0f0;
  background: #ffffff;
}

:deep(.create-doc-drawer .el-drawer__body) {
  padding: 0;
  display: flex;
  flex-direction: column;
  height: 100%;
}

.drawer-content {
  flex: 1;
  overflow-y: auto;
  padding-bottom: 80px; /* 为底部按钮留出空间 */
}

.drawer-footer {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 16px 24px;
  border-top: 1px solid #f0f0f0;
  background: #fafbff;
  display: flex;
  gap: 12px;
  justify-content: flex-end;
}

.drawer-header {
  padding: 20px 24px;
  background: #ffffff;
  border-bottom: 1px solid #f0f0f0;
}

.drawer-title {
  display: flex;
  align-items: center;
  gap: 12px;
  font-size: 18px;
  font-weight: 600;
  color: #374151;
}

.drawer-title .title-bar {
  width: 4px;
  height: 20px;
  background: linear-gradient(135deg, #5b7cff 0%, #a685ff 100%);
  border-radius: 2px;
}

.step-indicator {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 24px 0;
  background: #fafbff;
  border-bottom: 1px solid #f0f0f0;
  margin-bottom: 20px;
  position: relative;
}

.step-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  text-align: center;
}

.step-item.active .step-circle {
  background: linear-gradient(135deg, #5b7cff 0%, #a685ff 100%);
  color: white;
  box-shadow: 0 4px 12px rgba(91, 124, 255, 0.3);
}

.step-item.completed .step-circle {
  background: linear-gradient(135deg, #5b7cff 0%, #a685ff 100%);
  color: white;
  box-shadow: 0 4px 12px rgba(91, 124, 255, 0.3);
}

.step-item.active .step-title,
.step-item.completed .step-title {
  color: #5b7cff;
  font-weight: 600;
}

.step-circle {
  width: 36px;
  height: 36px;
  border-radius: 50%;
  background: #e5e7eb;
  color: #9ca3af;
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: 600;
  font-size: 14px;
  transition: all 0.3s ease;
  margin-bottom: 8px;
}

.step-info {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 4px;
}

.step-title {
  font-size: 14px;
  font-weight: 500;
  color: #374151;
  margin-bottom: 4px;
}

.step-desc {
  font-size: 12px;
  color: #9ca3af;
  line-height: 1.4;
}

.step-line {
  width: 100px;
  height: 2px;
  background: #e5e7eb;
  margin: 0 24px;
  position: relative;
  top: -25px;
  transition: all 0.3s ease;
}

.step-line.active {
  background: linear-gradient(90deg, #5b7cff 0%, #a685ff 100%);
}

.form-content {
  padding: 24px;
}

.form-item {
  margin-bottom: 28px;
}

.form-label {
  display: flex;
  align-items: center;
  gap: 10px;
  font-size: 15px;
  font-weight: 600;
  color: #374151;
  margin-bottom: 12px;
}

.form-label .el-icon {
  font-size: 18px;
}

.form-label .el-icon svg {
  width: 18px;
  height: 18px;
}

/* 图标颜色 */
.form-label:nth-child(1) .el-icon {
  color: #f59e0b; /* 文件夹图标 - 橙色 */
}

.form-item:nth-child(2) .form-label .el-icon {
  color: #10b981; /* 关键词图标 - 绿色 */
}

.form-item:nth-child(3) .form-label .el-icon {
  color: #3b82f6; /* 搜索图标 - 蓝色 */
}

.form-label-with-close {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}

.close-icon {
  color: #9ca3af;
  cursor: pointer;
  font-size: 18px;
  transition: color 0.3s ease;
}

.close-icon:hover {
  color: #ef4444;
}

:deep(.category-select .el-select__wrapper),
:deep(.keywords-select .el-select__wrapper),
:deep(.scope-select .el-select__wrapper) {
  border-radius: 8px;
  border: 1px solid #e5e7eb;
  transition: all 0.3s ease;
}

:deep(.category-select .el-select__wrapper:hover),
:deep(.keywords-select .el-select__wrapper:hover),
:deep(.scope-select .el-select__wrapper:hover) {
  border-color: #5b7cff;
  box-shadow: 0 0 0 3px rgba(91, 124, 255, 0.1);
}

.upload-area {
  border: 1px solid #e5e7eb;
  border-radius: 12px;
  overflow: hidden;
  background: white;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
}

.upload-zone {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 48px 20px;
  background: linear-gradient(135deg, #fafbff 0%, #f8f9ff 100%);
  border: 2px dashed #d1d5db;
  border-radius: 12px;
  cursor: pointer;
  transition: all 0.3s ease;
  position: relative;
}

.upload-zone:hover {
  border-color: #5b7cff;
  background: linear-gradient(135deg, #f0f4ff 0%, #e8f2ff 100%);
  transform: translateY(-2px);
  box-shadow: 0 8px 25px rgba(91, 124, 255, 0.15);
}

.upload-icon {
  margin-bottom: 20px;
  padding: 16px;
  background: white;
  border-radius: 50%;
  box-shadow: 0 4px 12px rgba(91, 124, 255, 0.15);
}

.upload-text {
  text-align: center;
}

.upload-title {
  font-size: 16px;
  color: #374151;
  margin-bottom: 8px;
  font-weight: 500;
}

.upload-link {
  color: #5b7cff;
  cursor: pointer;
  font-weight: 600;
  text-decoration: underline;
  text-underline-offset: 2px;
}

.upload-link:hover {
  color: #4c6ef5;
}

.upload-desc {
  font-size: 13px;
  color: #9ca3af;
  margin-top: 4px;
}

.uploaded-files-list {
  padding: 20px;
  background: #fafbfc;
  border-top: 1px solid #e5e7eb;
  max-height: 300px;
  overflow-y: auto;
}

.uploaded-file-item {
  display: flex;
  align-items: center;
  gap: 16px;
  padding: 16px;
  background: white;
  border-radius: 12px;
  margin-bottom: 12px;
  border: 1px solid #e5e7eb;
  transition: all 0.3s ease;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.02);
}

.uploaded-file-item:last-child {
  margin-bottom: 0;
}

.uploaded-file-item:hover {
  border-color: #5b7cff;
  box-shadow: 0 4px 12px rgba(91, 124, 255, 0.1);
  transform: translateY(-1px);
}

.file-icon {
  width: 48px;
  height: 48px;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;
  position: relative;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

.file-icon::before {
  content: '';
  position: absolute;
  top: 0;
  right: 0;
  width: 0;
  height: 0;
  border-style: solid;
  border-width: 0 12px 12px 0;
  border-color: transparent rgba(255, 255, 255, 0.3) transparent transparent;
  z-index: 2;
}

.file-type-badge {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 2px 0;
  background: rgba(0, 0, 0, 0.2);
  color: white;
  font-size: 10px;
  font-weight: 600;
  text-align: center;
  letter-spacing: 0.5px;
}

/* 文件类型图标样式 */
.file-icon-word {
  background: linear-gradient(135deg, #2B579A 0%, #1e3a8a 100%);
}

.file-icon-pdf {
  background: linear-gradient(135deg, #FF6B6B 0%, #dc2626 100%);
}

.file-icon-excel {
  background: linear-gradient(135deg, #217346 0%, #166835 100%);
}

.file-icon-ppt {
  background: linear-gradient(135deg, #D24726 0%, #b83b1e 100%);
}

.file-icon-txt {
  background: linear-gradient(135deg, #6B7280 0%, #4B5563 100%);
}

.file-icon-default {
  background: linear-gradient(135deg, #6B7280 0%, #4B5563 100%);
}

.file-info {
  flex: 1;
  min-width: 0;
}

.file-name {
  font-size: 15px;
  color: #374151;
  font-weight: 600;
  margin-bottom: 6px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.file-size {
  font-size: 13px;
  color: #9ca3af;
  font-weight: 500;
}

.file-actions {
  display: flex;
  gap: 12px;
  flex-shrink: 0;
}

.action-icon {
  width: 36px;
  height: 36px;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: all 0.3s ease;
  border: 1px solid #e5e7eb;
  background: white;
}

.preview-icon:hover {
  background: #f0f4ff;
  border-color: #5b7cff;
  color: #5b7cff;
  transform: scale(1.05);
}

.delete-icon:hover {
  background: #fef2f2;
  border-color: #ef4444;
  color: #ef4444;
  transform: scale(1.05);
}

/* 渐变按钮样式 */
.gradient-btn {
  background: linear-gradient(90deg, #5b7cff 0%, #a685ff 100%);
  border: none;
  color: white;
  padding: 10px 24px;
  border-radius: 6px;
  font-weight: 500;
  font-size: 14px;
  cursor: pointer;
  transition: all 0.3s ease;
  box-shadow: 0 2px 8px rgba(91, 124, 255, 0.3);
}

.gradient-btn:hover {
  background: linear-gradient(90deg, #4c6ef5 0%, #9c7eff 100%);
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(91, 124, 255, 0.4);
}

.gradient-btn:active {
  transform: translateY(0);
  box-shadow: 0 2px 6px rgba(91, 124, 255, 0.3);
}

/* 上传弹窗样式 */
:deep(.create-doc-dialog .el-dialog) {
  border-radius: 8px;
  overflow: hidden;
}

:deep(.create-doc-dialog .el-dialog__header) {
  padding: 0;
  margin-bottom: 0;
  border-bottom: 1px solid #f0f0f0;
  background: #ffffff;
}

.step-indicator {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 24px 0;
}

.step-item {
  display: flex;
  align-items: center;
  gap: 12px;
}

.step-item.active .step-circle {
  background: #5b7cff;
  color: white;
}

.step-item.active .step-title {
  color: #5b7cff;
  font-weight: 600;
}

.step-circle {
  width: 32px;
  height: 32px;
  border-radius: 50%;
  background: #e5e7eb;
  color: #9ca3af;
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: 600;
  font-size: 14px;
}

.step-info {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.step-title {
  font-size: 14px;
  font-weight: 500;
  color: #374151;
}

.step-desc {
  font-size: 12px;
  color: #9ca3af;
}

.step-line {
  width: 80px;
  height: 2px;
  background: #e5e7eb;
  margin: 0 24px;
}

.form-content {
  padding: 0 24px;
}

.form-item {
  margin-bottom: 24px;
}

.form-label {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 14px;
  font-weight: 500;
  color: #374151;
  margin-bottom: 8px;
}

.form-label-with-close {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}

.close-icon {
  color: #9ca3af;
  cursor: pointer;
  font-size: 16px;
}

.close-icon:hover {
  color: #ef4444;
}

.upload-area {
  border: 1px solid #e5e7eb;
  border-radius: 8px;
  overflow: hidden;
}

.upload-zone {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 40px 20px;
  background: #fafbfc;
  border: 2px dashed #d1d5db;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.upload-zone:hover {
  border-color: #5b7cff;
  background: #f8f9ff;
}

.upload-icon {
  margin-bottom: 16px;
}

.upload-text {
  text-align: center;
}

.upload-title {
  font-size: 14px;
  color: #374151;
  margin-bottom: 8px;
}

.upload-link {
  color: #5b7cff;
  cursor: pointer;
}

.upload-desc {
  font-size: 12px;
  color: #9ca3af;
}

.uploaded-files-list {
  padding: 16px;
  background: white;
  border-top: 1px solid #e5e7eb;
}

.uploaded-file-item {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 12px 0;
  border-bottom: 1px solid #f3f4f6;
}

.uploaded-file-item:last-child {
  border-bottom: none;
}

.file-info {
  flex: 1;
}

.file-name {
  font-size: 14px;
  color: #374151;
  font-weight: 500;
  margin-bottom: 4px;
}

.file-size {
  font-size: 12px;
  color: #9ca3af;
}

.file-actions {
  display: flex;
  gap: 8px;
}

.action-icon {
  width: 20px;
  height: 20px;
  cursor: pointer;
  transition: color 0.3s ease;
}

.preview-icon:hover {
  color: #5b7cff;
}

.delete-icon:hover {
  color: #ef4444;
}

:deep(.preview-dialog .el-dialog__body) {
  padding: 0;
  max-height: calc(90vh - 120px);
  overflow: hidden;
}

:deep(.preview-dialog .el-dialog__footer) {
  padding: 0;
  border-top: 1px solid #e5e7eb;
}

.preview-content {
  display: flex;
  flex-direction: column;
  height: calc(90vh - 120px);
}

.preview-file-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 16px 24px;
  background: #f8f9ff;
  border-bottom: 1px solid #e5e7eb;
}

.file-title {
  font-size: 14px;
  font-weight: 500;
  color: #333;
}

.file-status {
  display: flex;
  align-items: center;
}

.document-viewer {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.viewer-header {
  padding: 20px 24px;
  text-align: center;
  border-bottom: 1px solid #f0f0f0;
  background: white;
}

.viewer-title {
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 16px;
  font-weight: 500;
  color: #333;
  margin-bottom: 8px;
}

.viewer-subtitle {
  font-size: 14px;
  color: #666;
}

.document-content {
  flex: 1;
  padding: 24px;
  overflow-y: auto;
  background: white;
}

.content-section {
  margin-bottom: 32px;
}

.content-section:last-child {
  margin-bottom: 0;
}

.section-title {
  font-size: 16px;
  font-weight: 600;
  color: #333;
  margin-bottom: 16px;
  padding-bottom: 8px;
  border-bottom: 2px solid #5b7cff;
  display: inline-block;
}

.section-content {
  line-height: 1.8;
}

.section-content p {
  margin: 0 0 12px 0;
  font-size: 14px;
  color: #555;
  text-indent: 2em;
}

.section-content p:last-child {
  margin-bottom: 0;
}

.preview-actions {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  padding: 16px 24px;
  background: #f8f9ff;
}
.dialog-title{
  display: flex;
  align-items: center;
  gap: 12px;
  font-size: 18px;
  font-weight: 600;
  color: #333;
}

/* AI审核结果页面样式 */
/* .ai-review-content {
  padding: 24px;
}
 */
.review-header {
  margin-bottom: 24px;
  padding: 16px 20px;
  background: linear-gradient(135deg, #f8f9ff 0%, #f0f4ff 100%);
  border-radius: 12px;
  border: 1px solid #e8f2ff;
}

.review-info {
  display: flex;
  flex-wrap: wrap;
  gap: 24px;
}

.info-item {
  font-size: 14px;
  color: #374151;
  font-weight: 500;
}

.review-title {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 20px;
  font-size: 16px;
  font-weight: 600;
  color: #374151;
}

.title-icon {
  font-size: 20px;
  color: #5b7cff;
}

.review-count {
  margin-left: auto;
  font-size: 14px;
  color:#ff4d4f;
  font-weight: 400;
  background: #fff2f0;
  border: 1px solid #ffccc7;
  padding: 4px 12px;
  border-radius: 12px;
}

.review-results-list {
  display: flex;
  flex-direction: column;
  gap: 16px;
  max-height: 400px;
  overflow-y: auto;
}

.review-result-item {
  display: flex;
  align-items: center;
  gap: 16px;
  padding: 16px 20px;
  background: white;
  border-radius: 12px;
  border: 1px solid #e5e7eb;
  transition: all 0.3s ease;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.02);
}

.review-result-item:hover {
  border-color: #5b7cff;
  box-shadow: 0 4px 12px rgba(91, 124, 255, 0.1);
  transform: translateY(-1px);
}

.result-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.result-status {
  padding: 6px 16px;
  border-radius: 20px;
  font-size: 12px;
  font-weight: 500;
  white-space: nowrap;
  text-align: center;
  align-self: flex-start;
}

.result-status.success {
  background: #e8f5e8;
  color: #52c41a;
  border: 1px solid #b7eb8f;
}

.result-status.error {
  background: #fff2f0;
  color: #ff4d4f;
  border: 1px solid #ffccc7;
}

.result-filename {
  font-size: 14px;
  color: #374151;
  font-weight: 500;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.result-actions {
  display: flex;
  gap: 8px;
  flex-shrink: 0;
}

.result-actions .el-button {
  font-size: 12px;
  padding: 6px 12px;
}

/* 审核结果按钮样式 */
:deep(.review-action-btn.el-button--primary.is-plain) {
  color: #5b7cff !important;
  border-color: #5b7cff !important;
  background: transparent !important;
}

:deep(.review-action-btn.el-button--primary.is-plain:hover) {
  background: linear-gradient(90deg, #5b7cff 0%, #a685ff 100%) !important;
  color: white !important;
  border-color: transparent !important;
}

/* 禁用状态的按钮样式 */
:deep(.review-action-btn.el-button--primary.is-plain.is-disabled) {
  color: #c0c4cc !important;
  border-color: #e4e7ed !important;
  background: #f5f7fa !important;
  cursor: not-allowed !important;
}

.button-group {
  display: flex;
  gap: 12px;
}
.search-btn {
  background: linear-gradient(90deg, rgb(91, 124, 255) 0%, rgb(166, 133, 255) 100%);
  border: none;
  border-radius: 8px;
  padding: 8px 20px;
  font-weight: 600;
  box-shadow: 0 2px 8px rgba(102, 126, 234, 0.3);
  transition: all 0.3s ease;
}

.search-btn:hover {
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.4);
}

.reset-btn {
  background: linear-gradient(135deg, #f1f5f9 0%, #e2e8f0 100%);
  border: 1px solid #cbd5e1;
  color: #64748b;
  border-radius: 8px;
  padding: 8px 20px;
  font-weight: 600;
  transition: all 0.3s ease;
}

.reset-btn:hover {
  background: linear-gradient(135deg, #e2e8f0 0%, #cbd5e1 100%);
  transform: translateY(-1px);
}

/* 标签和关键词容器样式 */
.tags-container,
.keywords-container {
  display: flex;
  flex-wrap: wrap;
  gap: 4px;
  align-items: center;
}

.tag-item,
.keyword-item {
  margin: 0;
  border-radius: 12px;
  font-size: 11px;
  font-weight: 500;
  transition: all 0.2s ease;
}

.tag-item:hover,
.keyword-item:hover {
  transform: translateY(-1px);
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.more-tag,
.more-keyword {
  margin: 0;
  border-radius: 10px;
  font-size: 10px;
  font-weight: 600;
  background: #f5f7fa;
  border: 1px solid #e4e7ed;
  color: #909399;
  cursor: pointer;
  transition: all 0.2s ease;
}

.more-tag:hover,
.more-keyword:hover {
  background: #e4e7ed;
  color: #606266;
}

.no-data {
  color: #c0c4cc;
  font-style: italic;
}

/* 表格单元格内容垂直居中 */
:deep(.el-table .cell) {
  display: flex;
  align-items: center;
  min-height: 40px;
}

/* 标签和关键词列的特殊样式 */
:deep(.el-table .el-table__cell:nth-child(5) .cell),
:deep(.el-table .el-table__cell:nth-child(6) .cell) {
  justify-content: flex-start;
  padding: 8px 0;
}
</style>



